<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <img src="../assets/logo.png" alt="Logo" class="logo" />
        <h1>EB2 管理后台</h1>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="用户名" 
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="密码" 
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>© {{ new Date().getFullYear() }} EB2 管理后台</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminAPI } from '../api/api'
import { useAdminStore } from '../stores/admin'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const loginFormRef = ref(null)
const adminStore = useAdminStore()

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 检查是否已登录
onMounted(async () => {
  try {
    const result = await adminAPI.getStatus()
    // 如果已登录且当前在登录页，跳转到首页
    if (result.code === 200 && route.path === '/login') {
      ElMessage.success('您已登录，正在跳转到首页')
      setTimeout(() => {
        router.push('/')
      }, 1000)
    }
  } catch (error) {
    // console.error('检查登录状态失败', error)
    // 发生错误不做处理，保持在登录页
  }
})

// 登录处理函数
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      const loginData = {
        username: loginForm.username,
        password: loginForm.password
      }
      
      const result = await adminAPI.login(loginData)
      
      console.log('登录响应:', result)
      
      if (result.code === 200) {
        ElMessage.success('登录成功')
        
        // 使用 Pinia store 存储登录信息
        if (result.data) {
          adminStore.handleLoginSuccess(result.data)
        }
        
        // 预先获取菜单数据
        try {
          await adminAPI.getMenus()
          // 暂停片刻，确保token和菜单数据都已更新
          await new Promise(resolve => setTimeout(resolve, 300))
        } catch (menuError) {
          console.error('预加载菜单失败', menuError)
          // 继续导航流程，App.vue会重试加载菜单
        }
        
        // 使用路由跳转而不是刷新页面，避免页面闪烁
        router.push('/')
      } else {
        ElMessage.error(result.msg || '登录失败')
      }
    } catch (error) {
      console.error('登录出错:', error)
      if (error.response) {
        console.error('响应状态:', error.response.status)
        console.error('响应数据:', error.response.data)
      }
      ElMessage.error('登录失败，请检查后端服务是否启动')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: linear-gradient(135deg, #1976d2, #64b5f6);
}

.login-form-wrapper {
  width: 380px;
  padding: 40px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.login-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  border-radius: 4px;
  font-size: 16px;
  height: 44px;
}

.login-footer {
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style>
